<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

	public function firstuser ()
	{

		if ($this->auth->count_users() > 0)
			redirect('admin/login');

		// initialize data array
		$data = array();
		$data['email'] = NULL;
		$data['message'] = array(
			'type' => 'information',
			'content' => 'You are the first user of the system. Please Register!'
		);
		$data['base_url'] = base_url();

		if ($_SERVER['REQUEST_METHOD'] == 'POST')
		{

			// fetch post parameters
			$email = $this->input->post('email');
			$password = $this->input->post('password');
			$password_retype = $this->input->post('password_retype');

			// try to create user
			$result = $this->auth->create_user($email, $password, $password_retype);

			// if ok, redirect user to login page
			if ($result)
				redirect('admin/login');

			// else
			$data['email'] = $email;
			$data['message'] = array(
				'type' => 'error',
				'content' => 'Error trying to create user. Plese check if you mistyped your password confirmation or if it is too short...'
			);

		}

		$this->load->view('admin/register', $data);

	}

	public function index ()
	{

		// initialize data array
		$data = array();
		$data['email'] = NULL;
		$data['message'] = NULL;
		$data['base_url'] = base_url();

		if ($_SERVER['REQUEST_METHOD'] == 'POST')
		{

			// fetch post parameters
			$email = $this->input->post('email');
			$password = $this->input->post('password');

			// auth input data
			$auth = $this->auth->auth_user($email, $password);

			// check result
			if (is_null($auth))
				$data['message'] = array (
					'type' => 'error',
					'content' => 'Dados inválidos'
				);
			else if (is_null($auth['token']))
			{
				$data['email'] = $email;
				$data['message'] = array (
					'type' => 'error',
					'content' => $auth['active'] > 0 ? "Senha inválida. ({$auth['active']} tentativas restantes)" : 'Usuário bloqueado.'
				);
			}
			else
			{
				// save auth token on cookies
				$cookie = array(
					'name'   => 'auth_token',
					'value'  => $auth['token'],
					'expire' => 3 * 86400,
					'path'   => '/'
				);
				$this->input->set_cookie($cookie);
				// redirect
				redirect('admin');
			}

		}

		$this->load->view('admin/login', $data);

	}

	public function __construct ()
	{

		// parent constructor
		parent::__construct();

		// load helpers and models
		$this->load->helper('url');
		$this->load->model('auth/auth');

		// search cookies for auth token
		$auth_token = $this->input->cookie('auth_token');
		if ( is_string($auth_token) )
			redirect('admin');

	}

}
